// MyTreeCtrl.cpp : implementation file
//

#include "stdafx.h"
#include "TopMost.h"
#include "MyTreeCtrl.h"


#define UM_HIGHLIGHT (WM_USER+100)

#define TIMER_ID_HIGHLIGHT 1000

// CMyTreeCtrl

IMPLEMENT_DYNAMIC(CMyTreeCtrl, CTreeCtrl)

CMyTreeCtrl::CMyTreeCtrl() : m_hSelectedWnd( NULL )
, m_nTickCount( 0 )
{

}

CMyTreeCtrl::~CMyTreeCtrl()
{
}


BEGIN_MESSAGE_MAP(CMyTreeCtrl, CTreeCtrl)
	ON_WM_RBUTTONDOWN()
	ON_MESSAGE(UM_HIGHLIGHT, OnHighlight)
	ON_WM_TIMER()
END_MESSAGE_MAP()


// CMyTreeCtrl message handlers


void CMyTreeCtrl::OnRButtonDown(UINT nFlags, CPoint point)
{
	UINT nFlag  = 0;
	HTREEITEM treeItem = HitTest(point, &nFlag);
	if( TVHT_ONITEM & nFlag )
	{
		SelectItem( treeItem );

		HMENU menu = ::CreatePopupMenu();
		::AppendMenu(menu, MF_BYCOMMAND, 100, L"Highlight");
		CPoint pt(point);
		ClientToScreen(&pt);
		BOOL cmd = ::TrackPopupMenu(menu, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RETURNCMD , pt.x, pt.y, 0, m_hWnd, NULL);
		if( 100 == cmd )
		{
			::PostMessage(m_hWnd, UM_HIGHLIGHT, (WPARAM) treeItem, 0);
		}
		::DestroyMenu(menu);
	}
}

void CMyTreeCtrl::OnTimer(UINT_PTR nIDEvent)
{
	if( TIMER_ID_HIGHLIGHT == nIDEvent)
	{
		if ( ::IsWindowVisible( m_hSelectedWnd))
		{
			HDC hdc = ::GetWindowDC( m_hSelectedWnd );
			HPEN hNewPen = ::CreatePen(0, 3, RGB(0,0,255));

			CRect rc;
			::GetWindowRect(m_hSelectedWnd, &rc);
			rc -= rc.TopLeft();

			int oldRop2 = ::SetROP2(hdc, R2_NOTXORPEN);
			HGDIOBJ oldPen = ::SelectObject(hdc, hNewPen);

			::Rectangle(hdc, rc.left, rc.top, rc.right, rc.bottom);

			::SetROP2(hdc, oldRop2);
			::SelectObject(hdc, oldPen);

			::DeleteObject(hNewPen);
			::ReleaseDC(m_hSelectedWnd, hdc);

			if(++m_nTickCount == 6)
			{
				m_nTickCount = 0;
				::KillTimer(m_hWnd, TIMER_ID_HIGHLIGHT);
			}
		}
	}
}

LRESULT CMyTreeCtrl::OnHighlight(WPARAM wParam, LPARAM lParam)
{
	HTREEITEM treeItem = (HTREEITEM) wParam;

	CString str = GetItemText(treeItem);
	TCHAR* pWStr = str.GetBuffer(0);

	int nHwnd = 0;
	TCHAR *p = pWStr;
	while (*p != '\0' && *p != ' ')
	{
		if (*p <= 'f' && *p >='a') 
		{
			nHwnd = (nHwnd << 4) + (*p - 'a') + 10;
		}
		else if (*p <='F' && *p >= 'A')
		{
			nHwnd = (nHwnd << 4) + (*p - 'A') + 10;
		}
		else if (*p <='9' && *p >= '0')
		{
			nHwnd = (nHwnd << 4) + (*p - '0');
		}
		else
		{
			nHwnd = 0;
			break;
		}
		++p;
	}

	if (::IsWindowVisible(HWND(nHwnd)))
	{
		m_hSelectedWnd = (HWND) nHwnd;
		m_nTickCount = 0;
		::KillTimer(m_hWnd, TIMER_ID_HIGHLIGHT);
		::SetTimer(m_hWnd, TIMER_ID_HIGHLIGHT, 100, NULL);
	}
	else
	{
		m_hSelectedWnd = NULL;
		::KillTimer(m_hWnd, TIMER_ID_HIGHLIGHT);
	}

	return S_OK;
}